import math
import random
import time
from datetime import datetime

from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

from libs import config
from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow


def stoneworking(item_name):
    log_index, _ = game.get_backpack_index_and_qty(log_name)
    ac = ActionChains(driver)
    # 检查是否有工作台
    station_image = 'stone_station.png'
    stations = image_tool.find_all_targets(station_image)
    kit_name = 'Basic Stoneshaping Kit'
    buy_items = {}
    if len(stations) == 0:
        has_qty = game.get_backpack_qty(kit_name)
        if has_qty < 4:
            buy_items[kit_name] = 4 - has_qty
    if len(buy_items) > 0:
        trade_helper.goto_buy_position()
        filter_input = trade_helper.open_market_buy()
        for buy_name in buy_items:
            buy_qty = buy_items.get(buy_name)
            trade_helper.market_buy_item(filter_input, buy_name, buy_qty)
        action.escape()
        action.escape()
        action.goto_spec()
    if len(stations) == 0:
        spec_home = 'spec_home.png'
        (door_x, door_y) = image_tool.find_target(spec_home)
        kit_index, _ = game.get_backpack_index_and_qty(kit_name)
        game.use_backpack_item(kit_index)
        ac.reset_actions()
        ac.move_by_offset(door_x - 100, door_y - 40).click().perform()
        time.sleep(1)
        ac.move_by_offset(-120, 0).click().perform()
        time.sleep(1)
        ac.move_by_offset(0, -130).click().perform()
        time.sleep(1)
        ac.move_by_offset(120, 0).click().perform()
        time.sleep(1)
    movement.keep_move_up(2)
    movement.keep_move_left(1)
    time.sleep(1)
    stations = image_tool.find_all_targets(station_image)
    can_craft = True
    for _ in range(20):
        if not can_craft:
            break
        for (x, y) in stations:
            if not can_craft:
                break
            if craft(x, y, log_index, item_name) == 0:
                can_craft = False
    action.escape()
    action.escape()

def craft(x, y, log_index, cooking_item_name):
    try:
        for _ in range(20):
            if action.hover_bubble_text_has(x, y, 'Shaping in Progress'):
                time.sleep(5)
                continue
            else:
                break
        if action.hover_bubble_text_is(x, y, 'Ready'):
            action.click()
            time.sleep(0.5)

        if action.hover_bubble_text_is(x, y, 'Add 1 Log'):
            game.use_backpack_item(log_index)
            time.sleep(0.5)
            action.click()
            action.escape()
            time.sleep(0.5)
        if action.hover_bubble_text_is(x, y, 'Click to Stoneshape'):
            action.click()
            time.sleep(1)
            opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 3)
            if opt is None:
                action.escape()
                time.sleep(1)
                action.click()
                opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 10)
            opt.click()
            for _ in range(5):
                craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton',
                                                   2)
                if craft_button is None:
                    continue
                if craft_button.text == 'Collect':
                    if craft_button.is_enabled():
                        craft_button.click()
                        time.sleep(3)
                        continue
                if craft_button.text == 'Create':
                    if craft_button.is_enabled():
                        craft_button.click()
                        time.sleep(1)
                    else:
                        return 0
                    action.escape()
                    action.escape()
                    break
                time.sleep(1)
            return 1
        return 0
    except:
        return 0


def get_sell_price(order_items):
    target_price = None
    price_and_qty = {}

    for item in order_items:
        item_price = trade_helper.get_number(item.text.split(' @ ')[1])
        item_qty = trade_helper.get_number(item.text.split(' ')[0])
        price_and_qty[item_price] = price_and_qty.get(item_price, 0) + item_qty

    for price in price_and_qty:
        qty = price_and_qty.get(price)
        if qty < 33:
            continue
        elif qty < 100:
            target_price = int(price)
            break
        else:
            target_price = int(price) - 1
            break
    return target_price


def get_avg_buy_price(order_items, buy_qty):
    total_qty = 0
    total_cost = 0
    for item in order_items:
        price = trade_helper.get_number(item.text.split(' @ ')[1])
        qty = trade_helper.get_number(item.text.split(' ')[0])
        total_qty += qty
        total_cost += qty * price
        if total_qty > buy_qty:
            break
    return int(total_cost / total_qty)

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('StoneShaping')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id

    log = Log(user_id)
    driver = AdsWindow(user_id).open(False)
    game = Game(driver, user_id)
    action = WebDriverAction(driver)
    movement = Movement(driver)
    image_tool = ImageTool(driver)
    trade_helper = TradeHelper(driver, user_id)

    try:

        game.enter_game()
        game.collect_mail()
        snapshot = game.snapshot(user_id, 'before stoneshaping')
        log_name = 'Whittlewood Log'


        # 读取技能等级
        stone_skill = snapshot.get('skills').get('stone')

        print(stone_skill)
        if stone_skill < 8:
            # 低于8级在spec做Clayum Brick
            buy_items = {}
            powder_name = 'Clayum Powder'
            powder_qty = game.get_backpack_qty(powder_name)
            if powder_qty < 50:
                buy_items[powder_name] = 98 - powder_qty

            if game.get_backpack_qty(log_name) < 50:
                buy_items[log_name] = 50

            if len(buy_items) > 0:
                trade_helper.goto_buy_position()
                filter_input = trade_helper.open_market_buy()
                for buy_name in buy_items:
                    buy_qty = buy_items.get(buy_name)
                    buy_result = trade_helper.market_buy_item(filter_input, buy_name, buy_qty)
                action.escape()
            action.goto_spec()
            game.spec_drink_wine(500)
            stoneworking('Clayum Brick')
            # 检查技能等级
            skills = game.get_skills()
            task_helper.task_success()
            task_helper.stone()
        else:
            # 高于8级去MOI做Fireplace,做一个买一个，10分钟一次
            items = {
                "Clayum Brick": 12,
                "Scarrot": 12,
                "Whittlewood Plank": 24,
                "Silk Cloth": 12,
                "Glue": 2,
                "Stick": 36,
                "Construction Powder": 3,
                "Crafting Mix": 10
            }
            # buy_items = {}
            # for item_name in items:
            #     need_qty = items.get(item_name)
            #     has_qty = game.get_backpack_qty(item_name)
            #     if has_qty < need_qty:
            #         buy_items[item_name] = need_qty - has_qty
            #
            # if len(buy_items) > 0:
            #     trade_helper.goto_buy_position()
            #     filter_input = trade_helper.open_market_buy()
            #     for buy_name in buy_items:
            #         buy_qty = buy_items.get(buy_name)
            #         buy_result = trade_helper.market_buy_item(filter_input, buy_name, buy_qty)
            #     action.escape()

            moi_loc = action.goto_moi()

            # 制作
            action.click_by_offset(*moi_loc)

            cooking_item_name = "Fireplace"
            opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 3)
            if opt is None:
                action.escape()
                time.sleep(1)
                action.click()
                opt = action.find_element(By.XPATH, f"//span[text()='{cooking_item_name}']", cooking_item_name, 10)
            opt.click()
            time.sleep(1)

            craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)

            if craft_button.text == 'Collect':
                if craft_button.is_enabled():
                    craft_button.click()
                    time.sleep(3)
                    craft_button = action.find_element(By.CLASS_NAME, "Crafting_craftingButton__Qd6Ke", 'CraftButton', 2)

            if craft_button.text == 'Create':
                if craft_button.is_enabled():
                    craft_button.click()
                    action.escape()
                    action.escape()

            # task_helper.stone(delay_seconds=500)

            trade_helper.goto_sell_position()
            trade_helper.open_shop_sell()
            trade_helper.sell_item('Fireplace', 1111, price_delta=-1, min_price=66666)
            action.escape()
            movement.keep_move_right(1)

            task_helper.task_success()

    except Exception as e:
        task_helper.task_fail()
        task_helper.stone(retry=True)
        raise e